package com.gccloud.tgyfirst.controller.demo;

import com.gccloud.tgyfirst.service.demo.config.DemoConfig;
import com.gccloud.tgyfirst.service.demo.service.IFileService;

import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.gccloud.starter.common.vo.R;
import com.gccloud.starter.core.controller.SuperController;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiSort;
import org.apache.commons.io.FilenameUtils;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 下载上传文件
 * @author qianxing
 * @version 1.0
 * @date 2021/5/17 16:36
 */
@RestController
@RequestMapping("/file")
/**
 * 定义在swagger中展示文件上传下载模块，并且它的接口排序为 40
 */
@Api(tags = "文件上传下载")
@ApiSort(value = 40)
public class FileController extends SuperController {

    @Resource
    IFileService fileService;
    @Resource
    DemoConfig demoConfig;

    /**
     * 上传文件
     * @param file
     * @param response
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping("/upload")
    @ApiOperation(value = "上传", notes = "上传资源", produces = MediaType.APPLICATION_JSON_VALUE)
    public R<String> upload(@RequestParam("file") MultipartFile file, HttpServletResponse response, HttpServletRequest request) throws Exception {
        String name = IdWorker.getIdStr();
        String originalFilename = file.getOriginalFilename();
        String extension = FilenameUtils.getExtension(originalFilename);
        String objectName = name + "." + extension;
        if (StringUtils.isBlank(demoConfig.getFilePath())){
            R<String> r = new R<>();
            r.setCode(305);
            r.setMsg("上传失败，请检查文件存储路径！");
            return r;
        }
        String url = fileService.putObject(demoConfig.getFilePath(), objectName, file.getInputStream());
        return success(url);
    }


    /**
     * 下载文件
     * @param response
     * @param request
     * @throws IOException
     */
    @GetMapping("/download")
    @ApiOperation(value = "下载", notes = "下载资源", produces = MediaType.APPLICATION_JSON_VALUE)
    public void download(HttpServletResponse response, HttpServletRequest request) throws IOException {
        String fileName = demoConfig.getFileName();
        String filePath = demoConfig.getFilePath() + "/" + fileName;
        response.setContentType("application/x-msdownload");
        fileService.download(filePath, response.getOutputStream());
    }

}
